package ch.pizzapp.kurier;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import ch.pizzapp.kurier.client.InfoClient;
import ch.pizzapp.kurier.data.ResponceData;
import ch.pizzapp.kurier.data.SignUpResponceData;
import ch.pizzapp.kurier.data.UserResonce;
import ch.pizzapp.kurier.dto.InfoDto;
import ch.pizzapp.kurier.dto.UserDto;

import com.mobsandgeeks.saripaar.Rule;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.Validator.ValidationListener;
import com.mobsandgeeks.saripaar.annotation.ConfirmPassword;
import com.mobsandgeeks.saripaar.annotation.Email;
import com.mobsandgeeks.saripaar.annotation.Password;
import com.mobsandgeeks.saripaar.annotation.Required;
import com.mobsandgeeks.saripaar.annotation.TextRule;

/**
 * A placeholder fragment containing a simple view.
 */
@EFragment(R.layout.fragment_sign_up)
public class SignUpFragment extends Fragment {

	@Required(order = 1)
	@ViewById(R.id.fname)
	EditText fname;

	@Required(order = 2)
	@ViewById(R.id.lname)
	EditText lname;

	@ViewById(R.id.companyname)
	EditText companyname;

	@Required(order = 3)
	@ViewById(R.id.steet)
	EditText steet;

	@Required(order = 4)
	@ViewById(R.id.number)
	EditText number;

	@Required(order = 5)
	@ViewById(R.id.zipcode)
	EditText zipcode;

	@Required(order = 6)
	@ViewById(R.id.city)
	EditText city;

	@Required(order = 7)
	@Email(order = 2)
	@ViewById(R.id.email)
	EditText email;

	@Required(order = 8)
	@ViewById(R.id.phone)
	EditText phone;

	@Password(order = 9)
	@TextRule(order = 10, minLength = 6, message = "Enter at least 6 characters.")
	@ViewById(R.id.password)
	EditText password;

	@ConfirmPassword(order = 12)
	@ViewById(R.id.confirmpassword)
	EditText confirmpassword;

	@FragmentArg("ResponceData")
	ResponceData responceDataParce;

	private Validator validator;

	public SignUpFragment() {
	}

	public static SignUpFragment newInstance(ResponceData responceData) {
		SignUpFragment fragment = new SignUpFragment_();
		Bundle args = new Bundle();
		args.putParcelable("ResponceData", responceData);
		fragment.setArguments(args);
		return fragment;
	}

	@AfterViews
	void iniUI() {
		validator = new Validator(this);
		validator.setValidationListener(new RegistrationActivity());
	}

	@Click({ R.id.sign_up_button })
	void onClick(View view) {
		switch (view.getId()) {
		case R.id.sign_up_button:

			validator.validate();
			break;
		default:
			break;

		}
	}

	public class RegistrationActivity implements ValidationListener {

		public void onValidationSucceeded() {

			hideKeyboard(getActivity());
			showProgress(true);
			doSignUp();
		}

		public void onValidationFailed(View failedView, Rule<?> failedRule) {
			String message = failedRule.getFailureMessage();

			if (failedView instanceof EditText) {
				failedView.requestFocus();
				((EditText) failedView).setError(message);
			} else {
				showMessge(message);
			}
		}

	}

	public void hideKeyboard(Activity activity) {
		InputMethodManager inputMethodManager = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		// Find the currently focused view, so we can grab the correct window
		// token from it.
		View view = activity.getCurrentFocus();
		// If no view currently has focus, create a new one, just so we can grab
		// a window token from it
		if (view == null) {
			view = new View(activity);
		}
		inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}

	@Bean
	UserDto userdto;

	@RestService
	InfoClient infoClient;

	@Background
	void doSignUp() {
		userdto.setCity(city.getText().toString());
		userdto.setCompanyname(companyname.getText().toString());
		userdto.setEmail(email.getText().toString());
		userdto.setFname(fname.getText().toString());
		userdto.setNumber(number.getText().toString());
		userdto.setLname(lname.getText().toString());
		userdto.setPassword(password.getText().toString());
		userdto.setPhone(phone.getText().toString());
		userdto.setZipcode(zipcode.getText().toString());
		userdto.setSteet(steet.getText().toString());
		userdto.setType(2);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					setInfor(infoClient.doSignUp(userdto.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {
				showProgress(false);
				showMessge("Not connected ");
			}
		});
	}

	@UiThread
	void setInfor(final SignUpResponceData signUpResponceData) {

		showProgress(false);

		// System.out.println(signUpResponceData);

		if (signUpResponceData.getResponse() != null) {
			if (signUpResponceData.getResponse().getStatus().equals("1")) {
				showMessge("Successfully created");

				doLogin();

			} else {
				showMessge(signUpResponceData.getResponse().getMessage());
			}
		}

	}

	@Bean
	InfoDto infoDto;
	@RestService
	InfoClient InfoClient;

	@Background
	void doLogin() {

		infoDto.setPass(userdto.getPassword());
		infoDto.seteMail(userdto.getEmail());
		infoDto.setType("1");

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					setLogin(InfoClient.doLogin(infoDto.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("Not connected ");
			}
		});
	}

	@UiThread
	void setLogin(final UserResonce userResonce) {
		showProgress(false);
		if (userResonce.getResponse().getMessage() == null) {
			Intent intent = new Intent(getActivity(), PlacesActivity_.class);
			if (responceDataParce != null) {
				intent.putExtra("ResponceData", responceDataParce);
			}
			intent.putExtra("UserResonce", userResonce);
			startActivity(intent);

			getActivity().overridePendingTransition(R.anim.open_next,
					R.anim.close_main);
			getActivity().finish();
		} else {
			showMessge(userResonce.getResponse().getMessage());
		}

	}

	@UiThread
	void showMessge(final String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
	}

	@ViewById(R.id.login_status)
	protected LinearLayout mLoginStatusView;
	@ViewById(R.id.sing_up_form)
	ScrollView singUpForm;

	@UiThread
	void showProgress(final boolean show) {
		mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
		singUpForm.setVisibility(show ? View.GONE : View.VISIBLE);
	}

}